//
//  HZCartsListViewController.m
//  app
//
//  Created by khzliu on 15/5/5.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HZCartsListViewController.h"
#import "HZOrderConfirmViewController.h"
#import "HZGoodsDetailViewController.h"
#import "HDChatLIstController.h"

//view
#import "HZGoodsNumPicker.h"
#import "HZTableView.h"
#import "HZCartTableViewCell.h"
#import "HZCartTotalPanel.h"
#import "HZCartEmptyView.h"
#import "MyToast.h"
#import "HZProductGiftListView.h"
//model
#import "HZCartCellModel.h"
#import "HZCartTotalModel.h"
#import "HZCartListVCModel.h"
#import "HZRemoteResult.h"
//tools
#import "HZMallCartsHttpManager.h"
#import "HZBase64Handler.h"
//category
#import "UIAlertView+Conveniently.h"
#import "MBProgressHUD+Conveniently.h"
#import "JSONKit.h"
#import "HDChatOBO.h"

static const CGFloat kCartTotalPanelHeight = 90;

static const NSInteger kCartTotalPanelHasCannotBuyGoods = 2001;

@interface HZCartsListViewController ()
<UITableViewDelegate,
UITableViewDataSource,
HZCartTotalPanelDelegate,
HZCartTableViewCellDelegate,
HZGoodsNumPickerDelegate,
HZCartEmptyViewDelegate,
UIAlertViewDelegate>

@property (strong, nonatomic) HZTableView *tableView;
@property (strong, nonatomic) HZCartTotalPanel *cartTotalPanel;
@property (strong, nonatomic) HZGoodsNumPicker *goodsNumPicker;
@property (strong, nonatomic) HZCartEmptyView *cartEmptyView;


@property (strong, nonatomic) HZRemoteResult *remoteResult;
@property (strong, nonatomic) HZRemoteResult *deleteResult;
@property (strong, nonatomic) HZRemoteResult *addResult;
@property (strong, nonatomic) HZCartListVCModel *data;


@end

@implementation HZCartsListViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = NO;
    
    UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithTitle:self.title style:UIBarButtonItemStylePlain target:nil action:nil];
    UIImage* image = [UIImage imageNamed:@"ic_actionbar_home_up"];
    [back setBackButtonBackgroundImage:[image resizableImageWithCapInsets:UIEdgeInsetsMake(0, image.size.width, 0, 0)] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [back setBackButtonTitlePositionAdjustment:UIOffsetMake(2, 0) forBarMetrics:UIBarMetricsDefault];
    
    
    UIButton * chatBtn = [[UIButton alloc] initWithFrame:CGRectOf([self.ubo fx:1 ox:20 fy:0],
                                                                  [self.ubo ow:40 oh:40])];
    [chatBtn setImage:[UIImage imageNamed:@"chat_gz"] forState:UIControlStateNormal];
    chatBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [chatBtn addTarget:self action:@selector(rightBarBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:chatBtn];
    
    //[self.navigationController.navigationBar setBarTintColor:HZ_WHITE_COLOR];
    self.navigationController.navigationBar.backgroundColor = HZ_CLEAR_COLOR;
    
    self.view.frame = CGRectOf([UBO_WINDOW fx:UB_LEFT fy:UB_TOP],[UBO_WINDOW fw:UB_WIDTH fh:UB_HEIGHT]);
    
    //关闭自动适应UIScrollView
    self.automaticallyAdjustsScrollViewInsets = NO;
    //    Bar的模糊效果，默认为YES
    self.navigationController.navigationBar.translucent = YES;
    //添加tableView
    self.tableView = [[HZTableView alloc] initWithFrame:CGRectOf(CGPointMake(0, 0),
                                                                 [self.view.ubo fw:UB_WIDTH fh:UB_HEIGHT]) style:UITableViewStylePlain];
    self.tableView.backgroundColor = HZ_WHITE_COLOR;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.contentInset = UIEdgeInsetsMake(self.navigationAndStatusBarHeight, 0, ktabBarHeight+UF(kCartTotalPanelHeight), 0);
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(self.navigationAndStatusBarHeight, 0, ktabBarHeight+UF(kCartTotalPanelHeight), 0);
    self.tableView.headerRefreshController = [[UIRefreshHeaderController alloc] initWithTableView:self.tableView caller:[UBTargetCaller of:self action:@selector(refreshDataFromNotification)]];
    self.tableView.nothingRefreshView = [[UIRefreshNotingRefreshView alloc] initWithView:self.tableView viewController:self tryAgain:@selector(refreshDataFromNotification)];
    [self.view addSubview:self.tableView];
    
    //添加结算panel
    self.cartTotalPanel = [[HZCartTotalPanel alloc] initWithFrame:CGRectOf([self.view.ubo fx:UB_LEFT fy:UB_BOTTOM uy:-kCartTotalPanelHeight oy:-ktabBarHeight],
                                                                           [self.view.ubo fw:UB_WIDTH uh:kCartTotalPanelHeight])];
    self.cartTotalPanel.delegate = self;
    [self.view addSubview:self.cartTotalPanel];
    self.cartTotalPanel.hidden = YES;
    
    //添加pickerView
    self.goodsNumPicker = [[HZGoodsNumPicker alloc] initWithFrame:self.view.frame];
    self.goodsNumPicker.delegate = self;
    
    self.cartEmptyView = [[HZCartEmptyView alloc] initWithFrame:CGRectOf([self.view.ubo fx:UB_LEFT fy:UB_TOP oy:self.navigationAndStatusBarHeight],
                                                                         [self.view.ubo fw:UB_WIDTH fh:UB_HEIGHT])];
    self.cartEmptyView.delegate = self;
    [self.view addSubview:self.cartEmptyView];
    
    self.remoteResult = [HZRemoteResult target:self action:@selector(finishLoadData)];
    self.deleteResult = [HZRemoteResult target:self action:@selector(finishDeleteGoods)];

    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshDataFromNotification) name:kNotificationCartsRefresh object:nil];

    
    
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    
    self.navigationController.navigationBar.hidden = NO;
    
    if ([self checkUserLongin]) {
        [self.cartEmptyView hide];
        if (self.data == nil) {
            //刚进来进行数据加载
            [self.tableView.nothingRefreshView show];
            [self refreshData];
        }else{
            if (self.data.noMoreData) {
                //刚进来进行数据加载
                [self.tableView.nothingRefreshView show];
                [self refreshData];
            }else{
                [self.cartEmptyView hide];
            }
        }
    }else{
        /** 本地也没有数据 -write by khzliu */
        [self.cartEmptyView showWithLoginBtn:YES];
    }
    
}


- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
}

//销毁注册的通知
- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kNotificationCartsRefresh object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"addNewCommunity" object:nil];
    
    
}


//检查用户是否登录
- (BOOL)checkUserLongin{
    NSString *uid = [[NSUserDefaults standardUserDefaults] stringForKey:@"uid"];
    if (uid && uid.length>0) {
        return YES;
    }
    return NO;
}

//跳转到登陆接口
- (void)gotoLoginViewController{
//    self.navigationController.toolbarHidden = YES;
//    
//    
//    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"visitor"];
//    [[NSUserDefaults standardUserDefaults] synchronize];
//    
//    UIViewController * loginOut = [[UIStoryboard storyboardWithName:@"LogInOutStoryboard" bundle:nil] instantiateViewControllerWithIdentifier:@"login"];
//    loginOut.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:loginOut animated:YES];
    
    [SNTool shouldLoginFromController:self];
    
}

#pragma mark 接收通知刷新数据
- (void)refreshDataFromNotification{
    
    if ([self checkUserLongin]) {
        /** 如果已经登录，怎加载网络 -write by khzliu */
        [self refreshData];
    }else{
        
       /** 本地也没有数据 -write by khzliu */
        [self.cartEmptyView showWithLoginBtn:YES];

        [self.tableView endRefreshingAll];

    }
}

#pragma mark 下拉刷新
- (void)refreshData{
    
    HZMallCartsHttpManager *httpManager = [HZMallCartsHttpManager shareHttpRequestMananger];

    [httpManager loadMallCartListDataWithResult:self.remoteResult];
}

#pragma mark 完成数据加载
- (void)finishLoadData{
    
    [self.tableView.headerRefreshController endRefreshing];
    
    if (self.remoteResult.response.status == JKResponseServerError || self.remoteResult.response.status == JKResponseLocalError) {
        [self.tableView.nothingRefreshView activeStop];
        return;
    }else if (self.remoteResult.response.status == JKResponseOK) {
        [self.tableView.nothingRefreshView remove];
    
        self.data = (HZCartListVCModel *)self.remoteResult.info;
        [self.tableView reloadData];
        
        
        self.cartTotalPanel.model = self.data.panelModel;
        self.cartTotalPanel.hidden = NO;
        
        if (self.data.noMoreData) {
            
            [self.cartEmptyView showWithLoginBtn:![self checkUserLongin]];
        }else{
            [self.cartEmptyView hide];
        }
    }else if(self.remoteResult.response.status == JKResponseTail){
        self.data = (HZCartListVCModel *)self.remoteResult.info;
        [self.tableView.nothingRefreshView remove];
        [self.view bringSubviewToFront:self.cartEmptyView];
        [self.cartEmptyView showWithLoginBtn:![self checkUserLongin]];
        self.cartTotalPanel.hidden = YES;
        [self.tableView reloadData];
    }else{
        [self.tableView.nothingRefreshView activeStop];
        [UIAlertView alertWithTitle:@"" message:self.remoteResult.response.message];
    }
    
    if(self.data){
        self.tableView.bounces = YES;
        //重新计算购物车内数量
        [self reloadProductNumberInCarts];
    }
}

#pragma mark 完成删除商品
- (void)finishDeleteGoods{
    
    [self.tableView.headerRefreshController endRefreshing];
    
    if (self.deleteResult.response.OK) {
        [self.tableView.nothingRefreshView remove];
        [self.data deleteCellModel];
    }else{
        [MyToast showDefaultBottonWithText:@"删除商品失败"];
    }
    
    //重新计算购物车内数量
    [self reloadProductNumberInCarts];
    
    [self.tableView reloadData];
    
    self.cartTotalPanel.model = self.data.panelModel;
    
    if (self.data.noMoreData) {
        [self.cartEmptyView showWithLoginBtn:![self checkUserLongin]];
    }else{
        [self.cartEmptyView hide];
    }
}

#pragma mark 消息列表
- (void)rightBarBtnClicked:(id)sender{
    
    if ([SNTool shouldLoginFromController:self]) {
        return;
    }
    
    HDChatLIstController * chatList = [[HDChatLIstController alloc]init];
    chatList.hidesBottomBarWhenPushed = YES;
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"firstChat"]integerValue] == 0) {
        chatList.chatSign = @"0";
    }else
    {
        chatList.chatSign = @"1";
    }
    
    [self.navigationController pushViewController:chatList animated:YES];
}

#pragma mark UITableViewDelegate UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.data.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HZCartTableViewCell *cell = [HZCartTableViewCell cellWithTableView:(HZTableView *)tableView type:HZCartTableViewCellTypeShoppingCart];
    HZCartCellModel *model = [self.data fetchCellModelAtRow:indexPath.row];
    cell.delegate = self;
    cell.model = model;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HZCartCellModel *model = [self.data fetchCellModelAtRow:indexPath.row];
    return model.cellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
    HZCartCellModel *model = [self.data fetchCellModelAtRow:indexPath.row];
    HZGoodsDetailViewController *detailVC = [[HZGoodsDetailViewController alloc] init];
    detailVC.shopID = model.shopID;
    detailVC.productID = model.goodsID;
    detailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailVC animated:YES];
}

//先要设Cell可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

//定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

//进入编辑模式，按下出现的编辑按钮后
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    HZMallCartsHttpManager *httpManager = [HZMallCartsHttpManager shareHttpRequestMananger];
    
    HZCartTableViewCell *cell = (HZCartTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    HZCartCellModel *model = [self.data.dataArray objectAtIndex:indexPath.row];
    
    if ([self checkUserLongin]) {
        self.data.cellModelNeedToDelete = cell.model;
        
        NSString *goods = [NSString stringWithFormat:@"[{\"act_id\":\"%@\",\"shop_id\":\"%@\",\"product_id\":\"%@\",\"num\":\"%@\",\"gifts\":\"%@\"}]", model.actID, model.shopID, model.goodsID, model.goodsCountNum, model.giftModel?model.giftModel.product_id:@""];
        
        
        NSDictionary *params = @{APIKEY_mall_goods:[HZBase64Handler encodeBase64WithString:goods]};
        
        
        [httpManager deleteGoodsWithParams:params result:self.deleteResult];
    }
}

//以下方法可以不是必须要实现，添加如下方法可实现特定效果：

//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}
#pragma mark 计价面板代理
//选中全部
- (void)cartTotalPanelSelectAllWithPanel:(HZCartTotalPanel *)panel{
    HZCartTotalModel *panelModel = panel.model;
    [self.data choseAllModelWithFlag:panelModel.isAllSelected];
    
    
    [self.tableView reloadData];
    panel.model = self.data.panelModel;
}
//结账
- (void)cartTotalPanelCloseAccountWithPanel:(HZCartTotalPanel *)panel{
    //跳到订单确认页面
    if ([self checkUserLongin]) {
        if ([self.data.panelModel.totalGoodsNum integerValue] <= 0) {
            //[UIAlertView alertWithTitle:@"" message:@"请选择您要结算的商品"];
            [MyToast showDefaultBottonWithText:@"请选择您要结算的商品"];
            return;
        }
        
        NSString * myAreaID = [[NSUserDefaults standardUserDefaults] objectForKey:kMyAreaID];
        if (!myAreaID || !myAreaID.length || [myAreaID isEqualToString:@"0"]) {
            [MyToast showDefaultBottonWithText:@"亲,您还没绑定小区"];
            return;
        }
        
        NSMutableArray *goodsToBuyArray = [NSMutableArray array];
        for (HZCartCellModel *model in self.data.dataArray) {
            if (model.isSelected) {
                NSMutableDictionary *goods = [NSMutableDictionary dictionary];
                [goods setObject:model.actID forKey:APIKEY_mall_act_id];
                [goods setObject:model.shopID forKey:APIKEY_mall_shop_id];
                [goods setObject:model.goodsID forKey:APIKEY_mall_product_id];
                [goods setObject:model.goodsCountNum forKey:APIKEY_mall_num];
                [goods setObject:model.goodsPriceNow forKey:APIKEY_mall_price];
                [goods setObject:model.giftModel.product_id?model.giftModel.product_id:@"" forKey:APIKEY_mall_gifts];
                [goodsToBuyArray addObject:[goods JSONString]];
                
                if (!model.canBuy) {
                    [UIAlertView showAlertWithTitle:@"" message:@"您添加了无法支付的商品，请重新添加"];
                    return;
                }
            }
        }
        
        NSString *paramsStr = [NSString stringWithFormat:@"[%@]", [goodsToBuyArray componentsJoinedByString:@","]];

        self.navigationController.toolbarHidden = YES;
        
        HZOrderConfirmViewController *orderCfmVC = [[HZOrderConfirmViewController alloc] initWithParams:paramsStr];
        orderCfmVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:orderCfmVC animated:YES];
        
    }else{
        UIAlertView * av = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"登陆后可购买您喜欢的商品^_^" delegate:self cancelButtonTitle:nil otherButtonTitles:@"先逛逛",@"我要登陆", nil];
        [av show];
    }
}
#pragma mark - alterview 代理
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            //do nothing
        }
            break;
        case 1:
        {
            [self gotoLoginViewController];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark 点击cell中的代理
//点击选择按钮
- (void)cartTableViewCellSelectedWithCell:(HZCartTableViewCell *)cell{
    [self.data fillPanelModel];
    self.cartTotalPanel.model = self.data.panelModel;
}
//点击更改数量按钮
- (void)cartTableViewCellGoodsNumChangeWithCell:(HZCartTableViewCell *)cell finished:(void(^)(NSString *))complied{
    [self.goodsNumPicker showGoodsNumPickerWithCell:cell];
}
//点击查看赠品列表
- (void)cartTableViewCellGiftOnTouch:(HZCartCellModel *)model{
    NSString *pattern = @"";
    for (NSDictionary *dict in model.patterns) {
        if ([model.goodsID isEqualToString:[dict stringForKey:APIKEY_mall_product_id nilValue:@""]]) {
            pattern = [dict stringForKey:APIKEY_mall_name nilValue:@""];
            break;
        }
    }
    HZProductGiftListView *giftListView = [[HZProductGiftListView alloc] initWithGift:model.giftModel promotions:model.promotionArray url:model.picURL price:model.goodsPriceNow title:model.goodsTitle spec:pattern];
    [giftListView showGiftListView];
}
#pragma mark pickerviewDelegate 
//更改数量完成
- (void)goodsNumPickerDismissWithCell:(HZCartTableViewCell *)cell{
    cell.model = cell.model;
    
    /** 用户未登录则更改本地的商品个数 -write by khzliu */
    if (![self checkUserLongin]) {
        HZMallSqlDataManager *sqlManager = [HZMallSqlDataManager defaultManager];
        [sqlManager updateOfflineCartsCacheDataWithModel:cell.model];
    }
    
    [self.data fillPanelModel];
    self.cartTotalPanel.model = self.data.panelModel;
    
    //重新计算购物车内的商品数量
    [self reloadProductNumberInCarts];
}

#pragma mark  HZCartEmptyViewDelegate
//跳转到登录界面
- (void)cartEmptyViewLoginWithView:(HZCartEmptyView *)cartEmptyView{
    
    HZMallCartsHttpManager *httpManager = [HZMallCartsHttpManager shareHttpRequestMananger];
    if (![httpManager networkReachable]) {
        [MyToast showDefaultBottonWithText:@"网络连接异常"];
        return;
    }
    [self gotoLoginViewController];
}
//先去逛逛
- (void)cartEmptyViewGetAroundWithView:(HZCartEmptyView *)cartEmptyView{
    //跳到主页面
    self.tabBarController.selectedIndex = 0;
}

//重新计算购物车商品的数量
- (void)reloadProductNumberInCarts{
    NSInteger productsNum = 0;
    for (HZCartCellModel *model in self.data.dataArray) {
        productsNum += [model.goodsCountNum integerValue];
    }
    
    //记录本地购物车内商品的数量
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%ld", (long)productsNum] forKey:kHZUserProductNumInCarts];
    //发送通知 告知购物车数量已经改变
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotifacationUserProductNumInCartsChanged object:nil];
}


#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (alertView.tag == kCartTotalPanelHasCannotBuyGoods) {
        
    }
}



@end
